package com.lc.cehui.ui.activity.mine;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.cehui.R;
import com.lc.cehui.app.AppActivity;
import com.lc.cehui.base.BaseDialog;
import com.lc.cehui.dialog.MenuDialog;
import com.lc.cehui.http.request.ResumeBean;
import com.lc.cehui.http.request.ResumeDocaddApi;
import com.lc.cehui.http.request.ResumeListApi;
import com.lc.cehui.http.request.ResumeListDelApi;
import com.lc.cehui.http.request.ResumeListTopApi;
import com.lc.cehui.http.request.SendDocApi;
import com.lc.cehui.http.response.BaseBean;
import com.lc.cehui.http.response.RegisterBean;
import com.lc.cehui.http.response.SendDocBean;
import com.lc.cehui.other.IntentKey;
import com.lc.cehui.util.SPUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 简历管理
 */
public class MyResumeActivity extends AppActivity {

    private static final int REQUEST_CODE =200 ;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private BaseQuickAdapter adapter;
    private List<ResumeBean.DataBean> list = new ArrayList<>();
    private List<String> menulist = new ArrayList<>();
    private int id;
    private int is_top;
    private int is_default;
    private String path;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_myresume;
    }

    @Override
    protected void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter = new BaseQuickAdapter<ResumeBean.DataBean, BaseViewHolder>(R.layout.item_myresume,list) {
            @Override
            protected void convert(@NonNull BaseViewHolder baseViewHolder, ResumeBean.DataBean dataBean) {
                   if (dataBean.getType()==1){
                    baseViewHolder.setImageResource(R.id.img,R.mipmap.tuwen);
                   }else {
                       baseViewHolder.setImageResource(R.id.img,R.mipmap.wenjian);
                   }
                   baseViewHolder.setText(R.id.tv_title,dataBean.getTitle());
                   baseViewHolder.setText(R.id.tv_date,dataBean.getCreate_time()+"上传");
                baseViewHolder.getView(R.id.img_set).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        id = dataBean.getId();
                        menulist.clear();
                        is_top = dataBean.getIs_top();
                        is_default = dataBean.getIs_default();
                        if (dataBean.getType()==2){
                            menulist.add("删除");
                        }else {
                          if (dataBean.getIs_top()==0){
                              menulist.add("置顶");
                          }else {
                              menulist.add("取消置顶");
                          }
                            if (dataBean.getIs_default()==0){
                                menulist.add("默认");
                            }else {
                                menulist.add("取消默认");
                            }
                            menulist.add("删除");
                        }
                        showMenuDialog(menulist,dataBean.getType());
                    }
                });
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void showMenuDialog(List list,int type) {
        new MenuDialog.Builder(getActivity())
                .setList(list)
                .setTitle("请选择操作")
                .setListener(new MenuDialog.OnListener<String>() {
                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        switch (position) {
                            case 0:
//                             默认
                                if (type==2){
                                    resume_list_del(type);
                                }else {
                                    if (is_top==0){
                                        is_top=1;
                                    }else {
                                        is_top=0;
                                    }

                                    resume_list_top();
                                }

                                break;
                            case 1:
                                if (is_default==0){
                                    is_default=1;
                                }else {
                                    is_default=0;
                                }
//                                置顶
                                resume_list_top();

                                break;
                            case 2:
//                                删除

                                    resume_list_del(type);

                                break;

                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {

                    }
                }).show();
    }

    private void resume_list_top() {


        EasyHttp.post(this)
                .api(new ResumeListTopApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID,0)).setId(id).setIs_top(is_top).setIs_default(is_default))
                .request(new HttpCallback<RegisterBean>(this) {

                    @Override
                    public void onSucceed(RegisterBean data) {
                        toast(data.getMsg());
                        if (data.getCode().equals("200")) {
                            resume_list();
                        }

                    }
                });
    }

    private void resume_list_del(int type) {
        EasyHttp.post(this)
                .api(new ResumeListDelApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID,0)).setId(id).setType(type))
                .request(new HttpCallback<RegisterBean>(this) {

                    @Override
                    public void onSucceed(RegisterBean data) {
                      toast(data.getMsg());
                        if (data.getCode().equals("200")) {
                            resume_list();
                        }

                    }
                });
    }

    private void resume_list() {
        EasyHttp.post(this)
                .api(new ResumeListApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID,0)))
                .request(new HttpCallback<ResumeBean>(this) {

                    @Override
                    public void onSucceed(ResumeBean data) {

                        if (data.getCode().equals("200")) {
                            list.clear();
                            list.addAll(data.getData());
                            adapter.setNewData(list);
                            adapter.notifyDataSetChanged();
                        }

                    }
                });
    }


    @Override
    protected void initData() {


        resume_list();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.bt_submit)
    public void onClick() {
        pickFile();
    }
    public void pickFile() {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

        intent.addCategory(Intent.CATEGORY_OPENABLE);

        intent.setType("*/*");

        this.startActivityForResult(intent, REQUEST_CODE);

    }

    @Override

    protected void onActivityResult(final int requestCode, final int resultCode, @Nullable final Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (data==null){
            return;
        }
        if (resultCode == Activity.RESULT_OK&&requestCode==REQUEST_CODE) {//是否选择，没选择就不会继续
            if (resultCode == Activity.RESULT_OK) {
                             Uri uri = data.getData();
                             if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
                                   path = uri.getPath();

                                 send_doc(new File(path));
                                   return;
                               }
                           if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                                 path = getPath(this, uri);
                               send_doc(new File(path));

                                } else {//4.4以下下系统调用方法
                                    path = getRealPathFromURI(uri);
                               send_doc(new File(path));

                               }
                       }
               }


////

    }
    public String getRealPathFromURI(Uri contentUri) {
                 String res = null;
                String[] proj = { MediaStore.Images.Media.DATA };
               Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
                if(null!=cursor&&cursor.moveToFirst()){;
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    res = cursor.getString(column_index);
                      cursor.close();
                  }
               return res;
            }

            /**
       * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
       */
            @SuppressLint("NewApi")
     public String getPath(final Context context, final Uri uri) {

               final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

               // DocumentProvider
                if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                         // ExternalStorageProvider
                         if (isExternalStorageDocument(uri)) {
                                 final String docId = DocumentsContract.getDocumentId(uri);
                               final String[] split = docId.split(":");
                                final String type = split[0];
                                 if ("primary".equalsIgnoreCase(type)) {
                                         return Environment.getExternalStorageDirectory() + "/" + split[1];
                                    }
                            }
                       // DownloadsProvider
                        else if (isDownloadsDocument(uri)) {

                                 final String id = DocumentsContract.getDocumentId(uri);
                              final Uri contentUri = ContentUris.withAppendedId(
                                                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                                return getDataColumn(context, contentUri, null, null);
                            }
                       // MediaProvider
                        else if (isMediaDocument(uri)) {
                                 final String docId = DocumentsContract.getDocumentId(uri);
                               final String[] split = docId.split(":");
                               final String type = split[0];

                               Uri contentUri = null;
                              if ("image".equals(type)) {
                                       contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                                     } else if ("video".equals(type)) {
                                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                                    } else if ("audio".equals(type)) {
                                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                                   }

                              final String selection = "_id=?";
                                final String[] selectionArgs = new String[]{split[1]};

                               return getDataColumn(context, contentUri, selection, selectionArgs);
                           }
                   }
              // MediaStore (and general)
               else if ("content".equalsIgnoreCase(uri.getScheme())) {
                      return getDataColumn(context, uri, null, null);
                     }
                 // File
               else if ("file".equalsIgnoreCase(uri.getScheme())) {
                      return uri.getPath();
                    }
               return null;
             }

    public String getDataColumn(Context context, Uri uri, String selection,
                                 String[] selectionArgs) {

             Cursor cursor = null;
                 final String column = "_data";
                 final String[] projection = {column};

               try {
                      cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                                        null);
                        if (cursor != null && cursor.moveToFirst()) {
                              final int column_index = cursor.getColumnIndexOrThrow(column);
                             return cursor.getString(column_index);
                          }
                  } finally {
                       if (cursor != null)
                                cursor.close();
                  }
               return null;
            }

    public boolean isExternalStorageDocument(Uri uri) {
                return "com.android.externalstorage.documents".equals(uri.getAuthority());
            }

           /**
     * @param uri The Uri to check.
      * @return Whether the Uri authority is DownloadsProvider.
       */
            public boolean isDownloadsDocument(Uri uri) {
                return "com.android.providers.downloads.documents".equals(uri.getAuthority());
             }

           /**
     * @param uri The Uri to check.
      * @return Whether the Uri authority is MediaProvider.
      */
           public boolean isMediaDocument(Uri uri) {
              return "com.android.providers.media.documents".equals(uri.getAuthority());
          }
    private void send_doc(File  file) {
        EasyHttp.post(this)
                .api(new SendDocApi().setDoc(file))
                .request(new HttpCallback<SendDocBean>(this) {

                    @Override
                    public void onSucceed(SendDocBean data) {

                         if (data.getCode().equals("200")){
                             resume_docadd(data.getData().getDoc(),data.getData().getShow_doc());
                         }



                    }

                });
    }

    private void resume_docadd(String Doc,String Show_doc) {
        EasyHttp.post(this)
                .api(new ResumeDocaddApi().setDoc(Doc).setShow_doc(Show_doc).setUserid(SPUtil.get(this,IntentKey.USERID,0)))
                .request(new HttpCallback<BaseBean>(this) {

                    @Override
                    public void onSucceed(BaseBean data) {

                        if (callBackCode(data)){
                            toast(data.getMsg());
                        }



                    }

                });
    }

}
